package concurrent.wait_notify;


import java.util.LinkedList;

/**
 * 入队和出队
 */
public class Myqueue {

    private final int MAX_SIZE = 1000;

    private final LinkedList<String> queue = new LinkedList<>();


    /**
     * 添加一个元素，当达到最大长度时释放当前线程的锁
     *
     * @param element
     */
    public synchronized void addElement(String element) {
        try {
            if (queue.size() == MAX_SIZE) {
                wait();
            }
            queue.add(element);
            notifyAll();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 获取一个元素，队列为空时释放当前线程的锁
     *
     * @return
     */

    public synchronized String getElement() {
        String first = null;

        try {
            if (queue.size() == 0) {
                //释放锁，等待其他线程添加数据
                wait();
            }
            first = queue.getFirst();
            //唤醒在等待锁的线程
            notifyAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return first;
    }
}
